'use strict';
// 获取学校列表云函数

const db = uniCloud.database();
const schoolsCollection = db.collection('schools');

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('获取学校列表 - 参数', event);
	
	// 分页参数
	const page = event.page || 1;
	const pageSize = event.pageSize || 100;
	const skipCount = (page - 1) * pageSize;
	
	// 查询条件
	const query = {};
	if (event.keyword) {
		query.name = new RegExp(event.keyword, 'i');
	}
	
	try {
		// 查询学校列表
		const schoolsData = await schoolsCollection
			.where(query)
			.skip(skipCount)
			.limit(pageSize)
			.orderBy('create_date', 'desc')
			.get();
		
		// 如果没有数据，自动插入示例数据
		if (schoolsData.data.length === 0 && page === 1 && !event.keyword) {
			const exampleSchools = [
				{ name: '北京大学', code: '10001', region: '北京', level: '985' },
				{ name: '清华大学', code: '10002', region: '北京', level: '985' },
				{ name: '浙江大学', code: '10003', region: '浙江', level: '985' },
				{ name: '复旦大学', code: '10004', region: '上海', level: '985' },
				{ name: '上海交通大学', code: '10005', region: '上海', level: '985' },
				{ name: '南京大学', code: '10006', region: '江苏', level: '985' }
			];
			
			// 插入示例数据
			for (const school of exampleSchools) {
				await schoolsCollection.add(school);
			}
			
			// 再次查询
			const newSchoolsData = await schoolsCollection
				.where(query)
				.skip(skipCount)
				.limit(pageSize)
				.orderBy('create_date', 'desc')
				.get();
				
			return {
				code: 0,
				message: '获取学校列表成功，已自动添加示例数据',
				data: newSchoolsData.data
			};
		}
		
		return {
			code: 0,
			message: '获取学校列表成功',
			data: schoolsData.data
		};
	} catch (error) {
		console.error('获取学校列表异常', error);
		return {
			code: -1,
			message: '获取学校列表失败：' + error.message,
			data: null
		};
	}
}; 